import 'package:flutter/material.dart';

import 'package:flutter_jojo_test/test.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';

import 'package:video_player/video_player.dart';

class VideoUtils {
  List<VideoPlayerController?> list = [];
  List<String> urls = [];
  var dds = {}.obs;
  var controller = VideoPlayerController.network('').obs;

  var hasData = false.obs;
  int disposeCount = 5; //超出多少个释放内存
  int preloadCount = 5; //预加载数量
  void init(List<UserVideo> data, PageController pageController) async {
    var lists = data.map((e) => VideoPlayerController.network(e.url));
    list.addAll(lists);
    urls.addAll(data.map((e) => e.url));
    pageController.addListener(() {
      var p = pageController.page!;
      if (p % 1 == 0) {
        play(p ~/ 1);
      }
    });

    play(0);
  }

  Future<void> play(int index) async {
    await controller.value.pause();
    await controller.value.seekTo(const Duration(seconds: 0));

    hasData.value = false;
    await preload(index);
    if (list[index] != null) {
      controller.value = list[index]!;
    }
    controller.refresh();
    hasData.value = true;
    await list[index]?.play();
    for (int i = 0; i < list.length; i++) {
      if (i < index - disposeCount || i > index + disposeCount) {
        if (list[i]?.value.isInitialized == true) {
          list[i]?.dispose();
          list[i] = null;
        }
      } else {
        if (i > index && i < index + preloadCount) {
          preload(i);
        }
      }
    }
  }

  Future<void> preload(int index) async {
    if (list[index] == null) {
      list[index] = VideoPlayerController.network(urls[index]);
      await list[index]?.initialize();
      dds[list[index]?.dataSource] = list[index]?.value.aspectRatio;
      dds.refresh();
      await list[index]?.setLooping(true);
    } else {
      if (list[index]?.value.isInitialized == false) {
        await list[index]?.initialize();
        dds[list[index]?.dataSource] = list[index]?.value.aspectRatio;
        dds.refresh();
        await list[index]?.setLooping(true);
      }
    }
  }
}
